// @Author miaoqing
// @Date 2024/02/23 11:44:00
// @Desc
package logic

import (
	"core/command"
	"core/component/logger"
	"core/component/router"
	"core/network"
	"runtime/debug"
)

type OnlineClient struct {
	*network.NetConn
	srvID      string
	Router     *router.Router
	srvAddr    string
	handleMsgs []uint16
	proIndx    uint32
}

func (oc *OnlineClient) Init() {
	oc.Router = router.NewRouter()
	oc.Register()
}

func (oc *OnlineClient) Register() {
	oc.Router.Register(uint16(command.Command_GatewayForwardPacket_Server), oc.gatewayForwardPacketHandler)
	oc.Router.Register(uint16(command.Command_RegisterToGateway_Server), oc.registerHandler)
	oc.Router.Register(uint16(command.Command_ClientOnlineRet_Server), oc.clientOnlineHandler)
}

func (oc *OnlineClient) OnConnect() {
	logger.Infof("[连接] 建立连接 local:%s remote:%s", oc.LocalAddr(), oc.RemoteAddr())
}

func (oc *OnlineClient) OnClose() {
	// Online服连接断开
	if oc.srvID != "" {
		onlineServerMgrGetMe().removeServerClient(oc.srvID)
	}
	logger.Infof("[连接] Online服务器断开Gateway服务器连接 local:%v remote:%v", oc.LocalAddr(), oc.RemoteAddr())
}

func (oc *OnlineClient) OnMessage(data []byte) {
	defer func() {
		if err := recover(); err != nil {
			logger.Error("[server_client] panic ", err, "\n", string(debug.Stack()))
		}
	}()
	_, err := oc.Router.Route(data)
	if err != nil {
		logger.Error(err)
	}
}

func (oc *OnlineClient) Marshal(msgID uint16, msg interface{}) ([]byte, error) {
	return oc.Router.Marshal(msgID, msg)
}

func (oc *OnlineClient) sendMsg(cmd command.Command, msg interface{}) bool {
	return oc.AsyncSend(uint16(cmd), msg)
}
